/*
	Copyright (C) 2010 Salil Bhagurkar

	This file is part of k3

	k3 is free software: you can redistribute it and/or modify
	it under the terms of the GNU Lesser General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	k3 is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Lesser General Public License for more details.

	You should have received a copy of the GNU Lesser General Public License
	along with k3.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <shared.h>


/**
 * Write function of the driver
 * Converts to an fs tree at the referrer
 */
static int xmlp_write(struct fs *referrer, struct fs *this, struct buffer *buf, u32 offset, u32 count)
{
	return 0;
}


/**
 * Unparser zone
 * Converts an fs tree into xml
 */
 
static void xmlp_write_node(struct buffer *to, struct fs *node)
{
	buffer_write_data(to, "<", 0, 1);
	buffer_write_data(to, node->name, 0, strlen(node->name));
	if((node->flags & FSFLAGS_MODE_MASK) != 0) {
		u32 mode = node->flags & FSFLAGS_MODE_MASK;
		if(mode == FSFLAGS_MODE_READ) {
			buffer_write_data(to, " mode = \"", 0, 9);
			buffer_write_data(to, "Read", 0, 4);
			buffer_write_data(to, "\"", 0, 1);
		} else if(mode == FSFLAGS_MODE_WRITE) {
			buffer_write_data(to, " mode = \"", 0, 9);
			buffer_write_data(to, "Write", 0, 5);
			buffer_write_data(to, "\"", 0, 1);
		}
	}
	if(node->system) {
		if(node->system->fs) {
			char base_fs[MAX_FS_NAME_LEN];
			fsparse_get_path(base_fs, node->system->fs);
			buffer_write_data(to, " base = \"", 0, 9);
			buffer_write_data(to, base_fs, 0, strlen(base_fs));
			buffer_write_data(to, "\"", 0, 1);
		}
	}
	buffer_write_data(to, ">", 0, 1);
	buffer_write(to, &node->buf, 0, 0);
	
	struct fs *t = node;
	int err;
	err = fsiter_get_child(t);
	while(!err) {
		xmlp_write_node(to, t);
		err = fsiter_get_next(&t);
	}
	
	buffer_write_data(to, "</", 0, 2);
	buffer_write_data(to, node->name, 0, strlen(node->name));
	buffer_write_data(to, ">", 0, 1);
}
 

/**
 * Device read function
 * Returns xml from the referrer fs structure
 */
static int xmlp_read(struct fs *referrer, struct fs *this, struct buffer *buf, u32 offset, u32 count)
{
	xmlp_write_node(buf, referrer);
	return 0;
}

void register_xmlparse()
{
	struct fs *xmlp_fs = fs_create(FSFLAGS_DEVICE, "xmlp");
	u32 len;
	xmlp_fs->system = fs_create_system(0, xmlp_read, xmlp_write, fs_system_generic_rename, xmlp_fs);
	fs_link(fsparse_get("/devices/lib"), xmlp_fs);
	
	
	
/*	while(1) {
		arch_halt();
	}*/
}
